#include <cstdlib>
#include "swf.h"
#include "Bits.h"
using namespace swfstream;
void Bits::reset() {
	offset = 0;
	nbytes = 0;
	bits_num = 0;
}
int32 Bits::read_s(int bits, FILE* f) {
	uint32 r = read_bits(bits, f);
	if ((r >> (bits - 1)) != 0) { // r<0
		r |= (((uint) (-1)) << bits);
	}
	return *((int32*) &r);
}
uint32 Bits::read_u(int bits, FILE* f) {
	return read_bits(bits, f);
}
uint32 Bits::read_bits(int bits, FILE* f) {
	//	printf("reading bits(%d),offset=%d\n",bits,offset);
	if (bits > 32) {
		fprintf(stderr, "too long bits\n");
		exit(1);
	}
	bits_num += bits;
	uint32 r;
	if (offset > 0) { //n is data
		r = n & (((unsigned char) 0xff) >> offset);
		if (bits + offset <= 8) {
			r >>= (8 - offset - bits);
			offset += bits;
			if (offset == 8) {
				offset = 0;
			}
			return r;
		} else {
			bits -= 8 - offset;
		}
	} else {
		r = 0;
	}
	n = getc(f);
	//	puts("!!!!!!!byte");
	while (bits > 8) {
		bits -= 8;
		//		r*=256;
		r <<= 8;
		r += n;
		n = fgetc(f);
		nbytes++;
		//		puts("!!!!!!!byte");
	}
	byte tmp = n & (((unsigned char) 0xff) << (8 - bits));
	tmp >>= (8 - bits);
	r <<= bits;
	r += tmp;
	offset = bits;
	if (offset == 8) {
		offset = 0;
	}
	return r;
}

